<template>
  <div>
    <!-- 待回运旧件查询 -->
    <TopFilter ref="TopFilters" :list="topFilterInit" :cols="3" :collapse="collapse" labelWidth="110" @filterChange="changeHandle"></TopFilter>
    <!-- table -->
    <FilterTable
      ref="table"
      :columns="columns"
      :params="fetchParams"
      :dataSource="dataList"
      :datakey="'records'"
      :fetchapi="fetchApi"
      :onColumnsChange="onColumnsChange"
      :onRowSelectChange="selectChange"
    >
      <template slot="controls">
        <!--          <multiuse-button size="small" type="primary" :click="batchExamine.bind()" :disabled="disableds">批量生成标签</multiuse-button>-->
        <multiuse-button size="small" type="primary" :click="batchExamineList.bind()" :disabled="disableds">打印旧件清单</multiuse-button>
        <multiuse-button size="small" type="primary" :click="batchExamineDetails.bind()" :disabled="disableds">打印旧件标签</multiuse-button>
        <multiuse-button size="small" type="primary" :click="exportFileBtn.bind()">导出</multiuse-button>
      </template>
    </FilterTable>
    <Drawer :visible.sync="editVisible" :title="'待回运清单'" destroyOnClose width="60%" :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}">
      <EditForm @close="editClose" @save="editSave" :rowData="editData"></EditForm>
    </Drawer>
    <BasePrint ref="templateReturnList" :data="waitReturnLabelList" template="waitReturnLabel/list" :isPreview="false" />
    <BasePrint ref="templateReturnDetails" :data="printList" template="waitReturnLabel/details" />
    <img id="barcode" style="display: none" />
  </div>
</template>
<script>
import EditForm from './EditForm.vue';
import moment from 'moment';
import QRcode from 'qrcode';
import { exportExcelFile } from '@/utils/index';
import { getPartType } from '@/api/dictionary/index.js';
import {
  getPreReturnListForExport,
  getListByPage,
  getListByPageNew,
  getListForExport,
  generateLabelPostList,
  exporturl,
  generateLabelList, generateLabel, generateReturnList, getPreReturnListForExportNew
} from '@/api/usedPartsReturnManage/usedPartsReturn_DLR/usedPartsWaitReturnQuery';
import JsBarcode from "jsbarcode";
import { dictionary } from '@/utils/dictMixin';
import { getAppId } from '@/assets/js/auth';
export default {
  mixins: [dictionary],
  components: {
    EditForm,
  },
  data() {
    return {
      // 非单个禁用
      // single: true,
      single: false,
      // 非多个禁用
      multiple: true,
      dataList: [],
      editVisible: false,
      collapse: true,
      topFilterInit: this.topFilterInitFun(),
      columns: this.creatHeader(),
      fetchApi: getListByPageNew,
      fetchParams: {
        source: 'DLR',
        // returnType : 55851001,
        // beginApplyAt:    moment()
        //   .month(moment().month())
        //   .startOf('month')
        //   .format('YYYY-MM-DD HH:mm:ss'),
        // endApplyAt: moment()
        //   .month(moment().month())
        //   .endOf('month')
        //   .format('YYYY-MM-DD HH:mm:ss'),
        xhrAbort: true
      }, //ipa 接口
      selectedRows: [], //选中服务站
      editData: null,
      disableds: false,
      waitReturnLabelList: {
        rows:[{

        }]
      },
      printList: {
        rows: [{
          "cpId": "417b41c12873d02cdd6e0939dda1e858",
          "appId": "beijing",
          "warehouse": null,
          "dealer": "R110101",
          "dealerName": "北京北方伟业",
          "model": "EU5",
          "partCode": "011-1307-0080",
          "partName": null,
          "faultAppear": "555",
          "seriesId": 0,
          "evNo": null,
          "vin": "30D8DC45DEDD0D7E4",
          "purchaseDate": "2021年01月01日",
          "warrantyStartDate": "2021年01月01日",
          "repairDate": "2021年01月19日",
          "prodDate": "2020-12-30 00:00:00.0",
          "saleDate": "2021-01-01 00:00:00.0",
          "engineNo": null,
          "licenseNo": "吉A234",
          "mileage": "500",
          "claimNo": "CL20210903150712120451",
          "partsNo": "011-1307-0080",
          "number": "1.00",
          "partsName": "拉伸弹簧",
          "supName": "芜湖伯特利汽车安全系统股份有限公司",
          "supCode": "A553C01351",
          "section": null,
          "explainS": "555",
          "type": "售前索赔",
          "codeUrl": "202204112244365852516",
          "changeNo": "011-1307-0080",
          "change": "拉伸弹簧"
        }],
      }
    };
  },
  created() {
    // if (getAppId() == 'arcfox') {
    //   this.topFilterInit.find(x => x.fieldName == 'ifComm').itemList =this.createDictList('5543',[55431001])
    // }else{
    //   this.topFilterInit.find(x => x.fieldName == 'ifComm').itemList =this.createDictList('5543')
    // }
    // this.chuqi();
    // this.fetchParams.beginApplyAt = moment().startOf('week').format('YYYY-MM-DD HH:mm:ss');
    // this.fetchParams.endApplyAt = moment().endOf('week').format('YYYY-MM-DD HH:mm:ss');
    // this.topFilterInit.find(item => item.fieldName === 'beginApplyAt|endApplyAt').initialValue = [
    //   moment()
    //     .month(moment().month())
    //     .startOf('month')
    //     .format('YYYY-MM-DD HH:mm:ss'),
    //   moment()
    //     .month(moment().month())
    //     .endOf('month')
    //     .format('YYYY-MM-DD HH:mm:ss')
    // ];
    this.chuqi2();
  },
  methods: {
    onColumnsChange(columns) {
      this.columns = columns;
      this.single = columns.length != 1;
      this.multiple = !columns.length;
    },
    // 链接生成二维码
    async getqrcode(item, url) {
      if (item['codeUrl'].indexOf('base64') > -1) {
        console.log(0, '二维码无需重复转换')
        return
      }
      const setUrl = await QRcode.toDataURL(url);
      item['codeUrl'] = setUrl
      console.log('链接生成二维码=>', setUrl.length, setUrl)
    },
    async batchExamineList() {
      let str = '';
      let partCodes = '';
      if (this.selectedRows.length === 0) {
        this.$notify.error({title: '提示信息', message: '请勾选要打印的数据!'});
        return;
      }
      for (let i = 0; i < this.selectedRows.length; i++) {
        if (i < this.selectedRows.length - 1) {
          str += this.selectedRows[i].claimId + ',';
          partCodes += this.selectedRows[i].partCode + ',';
        } else {
          str += this.selectedRows[i].claimId
          partCodes += this.selectedRows[i].partCode;
        }
      }
      let res;
      if (this.selectedRows.length === 20) {
        //全部查询导出
        res = await generateReturnList(this.fetchParams)
      } else {
        res = await generateLabel({ claimId: str, partCode: partCodes, source: 'list' });
      }
      if (res.resultCode === 200) {
        this.waitReturnLabelList.rows = res.data;
        this.$nextTick(() => {
          this.$refs.templateReturnList.EXCUTE_PRINT();
        });
      }
    },
    async batchExamineDetails() {
      let str = '';
      let partCodes = '';
      if (this.selectedRows.length === 0) {
        this.$notify.error({title: '提示信息', message: '请勾选要打印的数据!'});
        return;
      }
      for (let i = 0; i < this.selectedRows.length; i++) {
        if (i < this.selectedRows.length - 1) {
          str += this.selectedRows[i].claimId + ',';
          partCodes += this.selectedRows[i].partCode + ',';
        } else {
          str += this.selectedRows[i].claimId
          partCodes += this.selectedRows[i].partCode;
        }
      }
      const res = await generateLabel({ claimId: str, partCode: partCodes });
      this.printList.rows = res.data
      // for (let i = 0; i < res.data.length; i++) {
      //   // console.log("rows", this.printList.rows[i])
      // }
      this.printList.rows.map((x) => {
        if (x.appId == "beijing") {
          x.logo = require('@/assets/img/beijing.png');
        } else {
          x.logo = require('@/assets/img/arcfox.png');
        }
        // url 转 二维码
        this.getqrcode(x, x.codeUrl);
      })
      console.log('231232131',this.printList)
      this.$nextTick(() => {
        this.$refs.templateReturnDetails.EXCUTE_PRINT();
      });
    },
    async batchExamine() {

      let str = '';
      this.selectedRows.map(x => {
        str += x.claimId + ',';
      });
      console.log(str);
      const res = await generateLabelPostList({ ids: str });
      this.printList.rows = res.data;
      this.printList.rows.map((x) => {
        if (x.appId == "beijing") {
          x.logo = require('@/assets/img/beijing.png');
        } else {
          x.logo = require('@/assets/img/arcfox.png');
        }
      })
      this.printList.rows.map((x) => {
        // url 转 条形码
        JsBarcode('#barcode', x.codeUrl);
        this.$nextTick(function () {
          x.codeUrl = document.getElementById('barcode').src;
        });
      });
      this.$nextTick(() => {
        this.$refs.templateReturnList.EXCUTE_PRINT();
      });

    },
    //返件类型下拉框
    // async chuqi() {
    //   console.log("===== 获取下拉框数据 ====== ")
    //   const res = await getPartType({type: 5585});
    //   console.log("==========", res)
    //   if (res.resultCode == 200) {
    //     this.topFilterInit.find(x => x.fieldName == 'returnType').initialValue = '';
    //     this.topFilterInit.find(x => x.fieldName == 'returnType').itemList = res.data.map(y => ({
    //       text: y.codeCnDesc,
    //       value: y.codeId
    //     }));
    //   }
    // },
    //索赔类型下拉框
    async chuqi2() {
      console.log("===== 获取下拉框数据 ====== ")
      const res = await getPartType({ type: 5501 });
      console.log("==========", res)
      if (res.resultCode == 200) {
        let map = new Map()
        let cmsClaimTypeArr = []
        //有重复数据，去重
        res.data.forEach(item => {
          if (!map.has(item['codeId'])) {
            map.set(item['codeId'], item)
            cmsClaimTypeArr.push(item)
          }
          this.topFilterInit.find(x => x.fieldName == 'cmsClaimType').initialValue = '';
          this.topFilterInit.find(x => x.fieldName == 'cmsClaimType').itemList = cmsClaimTypeArr.map(y => ({ text: y.codeCnDesc, value: y.codeId }));
        })
      }
    },
    // 导出
   async exportFileBtn() {
     try {
       // let params = { reportNo: "RE202103060001" }
       let params = {...this.fetchParams}
       let res = await getPreReturnListForExportNew(params);
       exportExcelFile(res.data, '待回运旧件列表')
     } catch (err) {
       console.warn(err)
     }
      // getPreReturnListForExport(this.fetchParams)
      // let res = await exporturl(json);
      // if (res.resultCode == 200) {
      //   this.$router.push('/admin/auth/oem/downloadCenter');
      // }
      // let beginSubmitDate = this.topFilterInit.find(x => x.fieldName == "beginApplyAt|endApplyAt").initialValue[0];
      // let endSubmitDate = this.topFilterInit.find(x => x.fieldName == "beginApplyAt|endApplyAt").initialValue[1];
      // if(!beginSubmitDate) {
      //   this.$notify.warning({ title: '提示信息', message: '申请开始日期不可为空！' });
      //   return
      // }
      // if(!endSubmitDate) {
      //   this.$notify.warning({ title: '提示信息', message: '申请结束日期不可为空！' });
      //   return
      // }
      // if(getAppId() == 'arcfox') {
      //   if (moment(moment(endSubmitDate).format('YYYY-MM-DD')).diff(moment(beginSubmitDate), 'months', true) > 12) {
      //     this.$notify.warning({ title: '提示信息', message: '申请日期跨度不可超过十二个月！' });
      //     return
      //   }
      // } else {
      //   if (moment(moment(endSubmitDate).format('YYYY-MM-DD')).diff(moment(beginSubmitDate), 'months', true) > 12) {
      //     this.$notify.warning({ title: '提示信息', message: '申请日期跨度不可超过十二个月！' });
      //     return
      //   }
      // }
      // let obj = Object.assign({}, this.fetchParams, {xhrAbort: false});
      // obj.beginApplyAt = this.topFilterInit.find(x => x.fieldName == "beginApplyAt|endApplyAt").initialValue[0];
      // obj.endApplyAt = this.topFilterInit.find(x => x.fieldName == "beginApplyAt|endApplyAt").initialValue[1];
      // console.log("=== 点击导出 ===")
      // getListForExport(obj).then(res => {
      //   exportExcelFile(res.data, '待回运旧件查询');
      // });
    },
    //选中
    selectChange(rows) {
      this.selectedRows = rows;
      this.disableds = this.selectedRows.length <= 0;
      console.log(this.selectedRows);
    },
    chooseOrderNo(val) {
      this.editData = val;
      console.log("编辑ID", val)
      this.editVisible = true;
    },
    editClose() {
      this.editVisible = false;
    },
    editSave() {
      this.editVisible = false;
      this.fetchParams = { ...this.fetchParams };
    },
    topFilterInitFun() {
      return [
        { type: 'INPUT', label: '索赔单号', fieldName: 'claimNo', placeholder: '请输入索赔单号...', initialValue: '' },
        { type: 'INPUT', label: '旧件代码', fieldName: 'partCode', placeholder: '请输入旧件代码...', initialValue: '' },
        { type: 'INPUT', label: '旧件名称', fieldName: 'partName', placeholder: '请输入旧件名称...', initialValue: '' },
        {
          type: 'SELECT',
          label: '索赔类型',
          fieldName: 'cmsClaimType',
          placeholder: '请选择索赔类型...',
          initialValue: '',
          itemList: []
        }
        // {type: 'RANGE_DATE', label: '申请时间', fieldName: 'beginApplyAt|endApplyAt', placeholder: '请输入', initialValue: '' ,rules: [{ required: true, message: '请选择日期', trigger: 'change' }]},
        // {type: 'SELECT', label: '车辆属性', fieldName: 'ifComm', placeholder: '请输入', initialValue: '',itemList: []},
        // {
        //   type: 'SELECT',
        //   label: '返件类型',
        //   fieldName: 'returnType',
        //   placeholder: '请选择返件类型...',
        //   initialValue: '',
        //   itemList: []
        // }

      ];
    },
    //搜索获取数据
    changeHandle(val) {
      // if(!val.beginApplyAt) {
      //   this.$notify.warning({ title: '提示信息', message: '申请开始日期不可为空！' });
      //   return
      // }
      // if(!val.endApplyAt) {
      //   this.$notify.warning({ title: '提示信息', message: '申请结束日期不可为空！' });
      //   return
      // }
      // if(getAppId() == 'arcfox') {
      //   if (moment(moment(val.endApplyAt).format('YYYY-MM-DD')).diff(moment(val.beginApplyAt), 'months', true) > 12) {
      //     this.$notify.warning({ title: '提示信息', message: '申请日期跨度不可超过十二个月！' });
      //     return
      //   }
      // } else {
      //   if (moment(moment(val.endApplyAt).format('YYYY-MM-DD')).diff(moment(val.beginApplyAt), 'months', true) > 12) {
      //     this.$notify.warning({ title: '提示信息', message: '申请日期跨度不可超过十二个月！' });
      //     return
      //   }
      // }
      this.fetchParams = Object.assign({}, this.fetchParams, val, { xhrAbort: false });
      console.log(val);
    },
    //table表头和数据源
    creatHeader() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          fixed: 'left',
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 80,
          align: 'center',
          render: props => {
            return (
              <div>
                <multiuse-button size="mini" type="text" onClick={() => this.chooseOrderNo(props.row)}>
                  查看
                </multiuse-button>
              </div>
            );
          }
        },
        { title: '索赔单号', dataIndex: 'claimNo', sorter: true },
        // { title: '车辆属性', dataIndex: 'ifComm', sorter: true,filterItems: this.createDictList('5543'),
        //   dictItems: this.createDictList('5543'),
        //   render: props => {
        //     return <span>{this.createDictText(props.row.ifComm, '5543')}</span>;
        //   } },
        { title: '主损件代码', dataIndex: 'mainPartCode', sorter: true },
        { title: '主损件名称', dataIndex: 'mainPartName', sorter: true },
        { title: '旧件代码', dataIndex: 'partCode', sorter: true },
        { title: '旧件名称', dataIndex: 'partName', sorter: true },
        { title: '数量', dataIndex: 'partCount', sorter: true },
        { title: '索赔类型', dataIndex: 'cmsClaimTypeStr', sorter: true },
        // {title: '返件类型', dataIndex: 'returnTypeName', sorter: true},
        // {title: '销毁件销毁时间', dataIndex: 'createdAt', sorter: true},
        { title: 'VIN', dataIndex: 'vin', sorter: true, width: 150 },
        { title: '车型名称', dataIndex: 'modelName', sorter: true },
        { title: '购车日期', dataIndex: 'saleDate', sorter: true, dateFormat: 'YYYY-MM-DD' },
        { title: '行驶里程', dataIndex: 'driveMile', sorter: true },
        { title: '旧件供应商', dataIndex: 'supName', sorter: true },
        // {title: '申请时间', dataIndex: 'applyAt', sorter: true, width: 140},
        // {title: '审核时间', dataIndex: 'checkAt', sorter: true, width: 140}
        { title: '故障描述', dataIndex: 'faultAppear', sorter: true },
      ];
    },
  }
};
</script>

<style lang="less" scoped></style>
